package sk.naive.talker.command;

import sk.naive.talker.*;
import sk.naive.talker.adapter.TagConsts;
import sk.naive.talker.props.PropertyStoreException;
import sk.naive.talker.util.*;

import java.rmi.RemoteException;
import java.util.Set;

/**
 *
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.25 $ $Date: 2005/01/25 21:57:04 $
 */
public abstract class AbstractPermissionCommand extends AbstractCommand {
	public void exec()
		throws CommandException,
		RemoteException, PropertyStoreException
	{
		String[] sa = Utils.splitWords(params, 2);
		if (sa.length == 0) {
			noParameter(user);
			if (Utils.ownsPermission(user, getPermissionName())) {
				user.send(validPermissions());
			}
			return;
		}
		User victim = commandDispatcher.getUserFinder().findUserByLogin(sa[0]);
		if (victim == null) {
			sendUserNotFoundMessage(sa[0]);
			return;
		}
		if (sa.length == 1) {
			noParameter(victim);
		} else {
			if (victim == user && !(Utils.ownsPermission(user, Consts.PERM_SUPERUSER))) {
				sendHelper().sendMessage(user, selfWarning());
				return;
			}
			withParameter(victim, sa[1]);
		}
	}

	protected String validPermissions() throws RemoteException {
		StringBuilder sb = new StringBuilder();
		for (String perm : (Set<String>) user.getProperty(getPropertyName()).validValues()) {
			Utils.addToBuffer(sb, perm, ", ");
		}

		if (sb.length() == 0) {
			sb.append(getString("message.none", user.getProperties()));
		}

		sb.insert(0,getString("permissionGrant.list", user.getProperties()));
		sb.append(Utils.tag(TagConsts.BR));
		return sb.toString();
	}

	protected abstract void noParameter(User victim) throws RemoteException, CommandException, PropertyStoreException;

	protected abstract void withParameter(User victim, String s) throws RemoteException, CommandException, PropertyStoreException;

	protected abstract String getPropertyName();

	protected abstract String getPermissionName();
}
